﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
using Slam.SharePoint;

namespace SlamCms.SharePoint.UtilityPages
{
	public partial class CopyTagsToTagList : LayoutsPageBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			SPSite siteCollection = SPControl.GetContextSite(HttpContext.Current);
			SPWeb rootWeb = siteCollection.RootWeb;
			SPContentType tagContentType = null;
			try
			{
				tagContentType = rootWeb.ContentTypes["Tag"];
			}
			catch { }
			if (tagContentType != null)
			{
				using (SPWeb globalSettingsSite = siteCollection.AllWebs["GlobalSettings"])
				{
					SPList tagsList = globalSettingsSite.Lists["Tags"];
					for(int i = 0; i < globalSettingsSite.Lists.Count; i++)
					{
						SPList list = globalSettingsSite.Lists[i];
						if (list.ID != tagsList.ID && list.ContentTypes.Contains(tagContentType))
						{
							foreach (SPListItem listItem in list.Items)
							{
								if (listItem.ContentType != null && listItem.ContentType.EqualsOrInherits(tagContentType.Name) && tagsList.GetItemBySlamId(Convert.ToString(listItem["SLAM ID"])) == null)
								{
									SPListItem newTagListItem = tagsList.AddItem();
									newTagListItem["ContentTypeId"] = listItem["ContentTypeId"];
									foreach (SPField field in tagContentType.Fields)
									{
										if (!field.ReadOnlyField)
										{
											newTagListItem[field.Id] = listItem[field.Id];
										}
									}
									globalSettingsSite.AllowUnsafeUpdates = true;
									newTagListItem.Update();
								}
							}
						}
					}
				}
			}
		}
	}
}
